import { defineStore } from "pinia"
import { onMounted, reactive, ref } from "vue"
import { get, post } from "@/utils/api"
import { MessagePlugin } from "tdesign-vue-next"

export const useAdminUserStore = defineStore("adminUser", () => {
  onMounted(async () => {
    await table.getData()
    await addDialog.getOptions()
  })
  // 通用模块
  const common = {
    formData: reactive({
      user_id: "",
      app_name: "",
      app_id: "",
      type: 0,
      body: "",
      status: 1,
      over_date: ""
    }),
    clear: () => {
      Object.assign(common.formData, {
        user_id: "",
        type: 0,
        body: "",
        status: 1,
        over_date: ""
      })
    },
    isForever: ref(true),
    typeOptions: [
      {
        label: "域名",
        value: 0
      },
      {
        label: "IP",
        value: 1
      }
    ],
    validator: {
      bodyValidator: (val: string) => {
        // 域名
        const domainPattern = /^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}$/
        // IP
        const ipPattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/
        if (common.formData.type === 0 && !domainPattern.test(val)) {
          return { result: false, message: "请输正确的域名", type: "error" }
        }
        if (common.formData.type === 1 && !ipPattern.test(val)) {
          return { result: false, message: "请输正确的IP", type: "error" }
        }
        return { result: true }

      }
    },
    rules: {
      user_id: [{ required: true, trigger: "change" }],
      app_name: [{ required: true, trigger: "change" }],
      app_id: [{ required: true, trigger: "change" }],
      body: [{ required: true, trigger: "change" }, { validator: (val: any) => common.validator.bodyValidator(val) }]
    }
  }
  // 添加模块
  const addDialog = {
    loading: ref(false),
    visible: ref(false),
    appNameValue: reactive({
      label: "",
      value: ""
    }),
    nameLists: [],
    getOptions: async () => {
      const data = await get("/api/program/getNameLists")
      addDialog.nameLists = data.map((item: { name: string, id: number }) => {
        return {
          label: item.name,
          value: item.id
        }
      })
      addDialog.appNameValue = addDialog.nameLists[0]
      common.formData.app_id = addDialog.appNameValue.value.toString()
      common.formData.app_name = addDialog.appNameValue.label
    },
    appNameChange: (app: { value: string, label: string }) => {
      common.formData.app_id = app.value.toString()
      common.formData.app_name = app.label
    },
    add: async ({ validateResult, firstError, e }: any) => {
      e.preventDefault()
      if (validateResult === true) {
        await addDialog.confirmAdd()
      } else {
        console.log("Validate Errors: ", firstError, validateResult)
      }
    },
    confirmAdd: async () => {
      addDialog.loading.value = true
      try {
        if (common.isForever.value) {
          common.formData.over_date = "2101-11-05"
        }
        const response = await post("/api/authorization/add", common.formData)
        MessagePlugin(response.status, response.message)
        if (response.status === "success") {
          addDialog.visible.value = false
          await table.getData()
          table.key.value++ // 重新渲染表格
        }
      } catch (err) {
        await MessagePlugin("error", "系统错误，请稍后再试~")
        console.log(err)
      } finally {
        addDialog.loading.value = false
      }
    }
  }

  // 删除模块
  const deleteDialog = {
    id: ref(),
    ids: ref([]),
    idsChange: (value: any) => {
      deleteDialog.ids.value = value
    },
    visible: ref(false),
    groupVisible: ref(false),
    loading: ref(false),
    groupLoading: ref(false),
    delete: (id: number | string) => {
      deleteDialog.visible.value = true
      deleteDialog.id.value = id
    },
    confirmDelete: async () => {
      deleteDialog.loading.value = true
      try {
        const response = await post("/api/authorization/delete", { id: deleteDialog.id.value })
        MessagePlugin(response.status, response.message)
        await table.getData()
        table.key.value++ // 重新渲染表格
      } catch (err) {
        console.log(err)
        await MessagePlugin("error", "系统错误，请稍后再试~")
      } finally {
        deleteDialog.loading.value = false
        deleteDialog.visible.value = false
      }
    },
    isGroupEmpty: async () => {
      if( deleteDialog.ids.value.length === 0){
        await MessagePlugin("error", "删除失败，数据为空！")
      }else{
        deleteDialog.groupVisible.value = true
      }
    },
    confirmDeleteGroup: async () => {
      try {
        const response = await post("/api/authorization/deleteGroup", { ids: deleteDialog.ids.value })
        MessagePlugin(response.status, response.message)
        await table.getData()
        table.key.value++ // 重新渲染表格
      } catch (err) {
        console.log(err)
        await MessagePlugin("error", "系统错误，请稍后再试~")
      } finally {
        deleteDialog.groupLoading.value = false
        deleteDialog.groupVisible.value = false
      }
    }

  }
  // 编辑模块
  const editDialog = {
    loading: ref(false),
    visible: ref(false),
    editId: ref(),
    formDataAssign: (row: any) => {
      editDialog.visible.value = true
      editDialog.editId.value = row.id
      row.user_id = row.user_id.toString()
      row.app_id = row.app_id.toString()
      Object.assign(common.formData, row)
    },
    edit: async ({ validateResult, firstError, e }: any) => {
      e.preventDefault()
      if (validateResult === true) {
        await editDialog.confirmEdit()
      } else {
        console.log("Validate Errors: ", firstError, validateResult)
      }
    },
    confirmEdit: async () => {
      editDialog.loading.value = true
      if (common.isForever.value) {
        common.formData.over_date = "2101-11-05"
      }
      try {
        const response = await post("/api/authorization/update", {
          id: editDialog.editId.value,
          data: common.formData
        })
        MessagePlugin(response.status, response.message)
        if (response.status === "success") {
          editDialog.visible.value = false
          await table.getData()
          table.key.value++ // 重新渲染表格
        }
      } catch (err) {
        console.log(err)
      } finally {
        editDialog.loading.value = false
      }
    }
  }
  // 表格模块
  const table = {
    data: ref([]),
    getData: async () => {
      table.loading.value = true
      try {
        table.data.value = await get("/api/user/getAll")
      } catch (err) {
        console.log(err)
      } finally {
        table.loading.value = false
      }
    },
    loading: ref(false),
    key: ref(0),
    searchData: ref(""),
    search: async () => {
      table.loading.value = true
      table.data.value = await post("/api/authorization/search", { body: table.searchData.value })
      table.loading.value = false
    },
    refresh: async () => {
      await table.getData()
      table.key.value++
      table.searchData.value = ""
    }
  }

  return {
    addDialog,
    table,
    common,
    editDialog,
    deleteDialog
  }
})
